import DataServe from '@/api/article'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { ArticleDetail, CommentRes } from '@/types/data'
import { AppDispatch } from '@/types/store'

const articleSlice = createSlice({
  name: 'search',
  initialState: {
    articleInfo: {} as ArticleDetail,
    comment: {} as CommentRes
  },
  reducers: {
    setArticleInfo(state, action: PayloadAction<ArticleDetail>) {
      state.articleInfo = action.payload
    },
    setCommentList(state, action: PayloadAction<CommentRes>) {
      const oldComment = state.comment.results || []
      state.comment = {
        ...action.payload,
        results: [...oldComment, ...action.payload.results]
      }
    }
  }
})

export const { setArticleInfo, setCommentList } = articleSlice.actions

// 获取文章详情
export function getArticleInfoAsync(payload: string) {
  return async (dispatch: AppDispatch) => {
    const { data } = await DataServe.getArticleInfo(payload)
    dispatch(setArticleInfo(data))
  }
}
// 获取文章评论
export function getCommentListAsync(payload: { type: string; source: string; offset?: string }) {
  return async (dispatch: AppDispatch) => {
    const { data } = await DataServe.getCommentList(payload)
    dispatch(setCommentList(data))
  }
}
// 文章点赞/取消点赞操作
export function updateLinkingsAsync(payload: { attitude: number; id: string }) {
  return async () => {
    if (payload.attitude === 1) {
      await DataServe.cancelLinkings(payload.id)
    } else {
      await DataServe.sendLinkings(payload.id)
    }
  }
}
// 文章收藏/取消收藏操作
export function updateCollectionsAsync(payload: { is_collected: boolean; id: string }) {
  return async () => {
    if (payload.is_collected) {
      await DataServe.cancenCollections(payload.id)
    } else {
      await DataServe.sendCollections(payload.id)
    }
  }
}
export default articleSlice.reducer
